package com.example.springsecuritydemo2.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.springsecuritydemo2.common.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 客户端进行认证数据的提交时，或者是匿名用户访问受限资源的处理器
 */
@Component
public class AnonymousAuthenticationHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        ServletOutputStream outputStream = response.getOutputStream();
        String jsonString = "";
        if(authException instanceof BadCredentialsException){
            jsonString = JSON.toJSONString(R.error().message(authException.getMessage()).code(401), SerializerFeature.DisableCircularReferenceDetect);
        }else if (authException instanceof InternalAuthenticationServiceException){
            jsonString = JSON.toJSONString(R.error().message("用户名为空").code(401), SerializerFeature.DisableCircularReferenceDetect);
        }else{
            jsonString = JSON.toJSONString(R.error().message("用户名或者密码错误").code(401), SerializerFeature.DisableCircularReferenceDetect);
        }
        outputStream.write(jsonString.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
